<script setup lang="ts">
import {
  computed,
  nextTick,
  onBeforeUnmount,
  onMounted,
  onUpdated,
  ref,
  toRefs,
  watch,
} from 'vue';
import { formatValue } from '@/components/PriceComponent/utils';

type ValueInputFieldProps = {
  value: string;
  forceEdit: boolean;
};

type ValueInputFieldEmits = {
  (e: 'change', value: string): void;
};

const props = withDefaults(defineProps<ValueInputFieldProps>(), {
  forceEdit: false,
});
const emit = defineEmits<ValueInputFieldEmits>();

const { value: originalValue } = toRefs(props);
const innerValue = ref(originalValue.value);

const isFocused = ref(false);
const isEditing = ref(props.forceEdit);
const inputRef = ref(null);

const handleFocus = (event: Event) => {
  isFocused.value = true;
  nextTick(() => (event.target as HTMLInputElement).select());
};

const handleBlur = () => {
  isFocused.value = false;

  if (!innerValue.value.length) {
    innerValue.value = props.value;
  }

  emit('change', innerValue.value);

  if (!props.forceEdit) {
    isEditing.value = false;
  }
};

const handleInput = (event: Event) => {
  innerValue.value = (event.target as HTMLInputElement).value;
};

const handleCancel = () => {
  innerValue.value = props.value;
};

const handleEditClick = () => {
  isEditing.value = true;

  nextTick(() => {
    if (inputRef.value) {
      const element = inputRef.value as unknown as HTMLInputElement;
      element.focus();
      element.select();
    }
  });
};
</script>

<template>
  <div class="price-component__label">
    <span
      class="price-component__label-text"
      v-if="!isEditing"
      :title="props.value"
    >
      {{ props.value }}
    </span>
    <input
      ref="inputRef"
      v-else
      placeholder="Label"
      type="text"
      :value="innerValue"
      @input="handleInput"
      @focus="handleFocus"
      @blur="handleBlur"
      @keydown.esc.stop="handleCancel"
      :title="props.value"
    />
    <span class="material-icons" @click="handleEditClick">mode_edit</span>
  </div>
</template>

<style scoped lang="scss"></style>
